package com.future.dbutils;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class TransactionUtils {

	private static Logger logger = LogManager.getLogger(TransactionUtils.class);

	protected static DatabasePool databasePool = DatabasePool.getInstance();
	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

	public static Connection getConnection() {
		Connection conn = threadLocal.get();
		try {
			if (conn == null)
				conn = databasePool.getDataSource().getConnection();
			threadLocal.set(conn);
		} catch (SQLException e) {
			logger.error(e);
		}
		return conn;
	}

	public static void startTransaction() {
		Connection conn = getConnection();
		if (conn != null) {
			try {
				conn.setAutoCommit(false);
			} catch (SQLException e) {
				logger.error(e);
			}
		}
	}

	public static void commitTransaction() {
		Connection conn = getConnection();
		if (conn != null) {
			try {
				conn.commit();
			} catch (SQLException e) {
				logger.error(e);
				rollbackTransaction();
			} finally {
				closeConnection();
			}
		}
	}

	public static void rollbackTransaction() {
		Connection conn = getConnection();
		if (conn != null) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				logger.error(e);
			}
		}
	}

	public static void closeConnection() {
		Connection conn = getConnection();
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.error(e);
			} finally {
				threadLocal.remove();
			}
		}
	}

	public static void release() {

	}
}
